<script setup lang="ts">
  import { Ref, ref, watch } from 'vue';
  import { UserData } from '@/api/user/types';
  import { getRoleList } from '@/api/role';
  import { RoleData } from '@/api/role/types';
  import { FormInstance, Message } from '@arco-design/web-vue';
  import { createUser, editUser, getUserDetail } from '@/api/user';

  const props = defineProps({
    dialogVisiable: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
  });
  const roleList: Ref<RoleData[]> = ref([]);
  const addForm: Ref<UserData> = ref({
    id: undefined,
    username: '',
    enable: 1,
    gender: 1,
    avatar: '',
    address: '',
    email: '',
    nickName: '',
    roleIds: [],
    remark: '',
  });
  const formRules: FormInstance['rules'] = {
    username: [{ required: true, message: '用户名不能为空' }],
    nickName: [{ required: true, message: '昵称不能为空' }],
    email: [{ required: true, message: '电子邮件不能为空' }],
    address: [{ required: true, message: '地址不能为空' }],
    roleIds: [{ required: true, message: '请选择角色' }],
  };
  const emit = defineEmits(['dialogStatus', 'saveSuccess']);
  const formRef = ref();
  const saveId = ref();
  // 使用 watch 监听 dialogVisiable 的值
  watch(
    () => props.dialogVisiable,
    async () => {
      if (props.dialogVisiable) {
        const result = await getRoleList();
        roleList.value = result.data;
      }
    },
  );
  // 保存
  const handleSave = async () => {
    try {
      const isInvalid = await formRef.value?.validate();
      if (isInvalid) return false;
      // 保存和编辑
      if (saveId.value) {
        await editUser(addForm.value);
      } else {
        delete addForm.value.id;
        await createUser(addForm.value);
      }
      // 关闭对话框
      emit('saveSuccess');
      Message.success('保存成功');
      return true;
    } catch (error) {
      return false;
    }
  };
  // 编辑
  const handleEdit = async (id: number) => {
    saveId.value = id;
    const result = await getUserDetail(id);
    addForm.value = result.data;
  };
  // 点击关闭-取消按钮后触发
  const handleCancel = () => {
    emit('dialogStatus', false);
  };
  // 对话框关闭后触发
  const handleClose = () => {
    formRef.value.resetFields();
    saveId.value = undefined;
  };

  // 暴露方法
  defineExpose({
    handleEdit,
  });
</script>

<template>
  <a-modal
    :visible="dialogVisiable"
    title-align="start"
    :ok-text="$t('modal.operation.save')"
    :cancel-text="$t('modal.operation.cancel')"
    unmount-on-close
    @before-ok="handleSave"
    @close="handleClose"
    @cancel="handleCancel"
  >
    <template #title
      >{{
        saveId
          ? $t('searchTable.operation.edit')
          : $t('searchTable.operation.create')
      }}
    </template>
    <a-form ref="formRef" :rules="formRules" :model="addForm" auto-label-width>
      <a-form-item field="username" label="用户名">
        <a-input
          v-model="addForm.username"
          allow-clear
          placeholder="请输入用户名"
        ></a-input>
      </a-form-item>
      <a-form-item field="nickName" label="昵称">
        <a-input
          v-model="addForm.nickName"
          placeholder="请输入昵称"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="email" label="邮件">
        <a-input
          v-model="addForm.email"
          placeholder="请输入电子邮件"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="roleIds" label="角色">
        <a-select v-model="addForm.roleIds" placeholder="请选择角色" multiple>
          <a-option v-for="item in roleList" :key="item.id" :value="item.id"
            >{{ item.name }}
          </a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="address" label="地址">
        <a-textarea
          v-model="addForm.address"
          placeholder="请输入地址"
          allow-clear
          auto-size
          show-word-limit
        />
      </a-form-item>
      <a-form-item field="enable" label="状态">
        <a-switch
          v-model="addForm.enable"
          :checked-value="1"
          :unchecked-value="0"
          checked-text="开启"
          unchecked-text="关闭"
          type="round"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped lang="less"></style>
